package com.bozhong.config.parser;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author fupan
 */
public class NacosDataJsonParser extends AbstractNacosDataParser {
	public NacosDataJsonParser() {
		super("json");
	}

	@Override
	protected Map<String, Object> doParse(String data) throws IOException {
		if (StringUtils.isEmpty(data)) {
			return null;
		} else {
			Map<String, Object> map = this.parseJSON2Map(data);
			return this.reloadMap(map);
		}
	}

	private Map<String, Object> parseJSON2Map(String json) throws IOException {
		Map<String, Object> result = new LinkedHashMap(32);
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> nacosDataMap = (Map)mapper.readValue(json, LinkedHashMap.class);
		if (CollectionUtils.isEmpty(nacosDataMap)) {
			return result;
		} else {
			this.flattenedMap(result, nacosDataMap, "");
			return result;
		}
	}
}
